<?php

namespace app\common\repository\user;

use think\Db;
use app\common\model\user\User as UserModel;

class R
{
    public function _construct(
        UserModel $userModel
    ) {
        $this->userModel = $userModel;
    }

    public function getUser($cond)
    {
        return UserModel::where($cond)
            ->with(['tag', 'profile', 'saying', 'weixin', 'statistics'])
            ->find();
    }

    public function getUsers($cond)
    {
        return UserModel::hasWhere('profile', [$cond])
            ->with(['profile'])
            ->select();
    }

    public function getUserByArticleId($id)
    {
        return UserModel::hasWhere('article', ['id' => $id])
            ->with(['tag', 'profile', 'saying', 'weixin', 'statistics'])
            ->find();
    }

    public function getUserByBookId($id)
    {
        return UserModel::hasWhere('book', ['id' => $id])
            ->with(['tag', 'profile', 'saying', 'weixin', 'statistics'])
            ->find();
    }

    public function getTopUsers()
    {
        $topUserSql = '
        SELECT
            up.user_id as id, up.nickname as name, up.avatar as avatar, COUNT(up.user_id) as num
        FROM
            article a LEFT JOIN user_profile up
        ON
            a.user_id =  up.user_id
        GROUP BY
        up.user_id
        ';
        return Db::query($topUserSql);
    }

    public function getUserProfile($cond)
    {
        return UserModel::with(['tag', 'profile', 'saying', 'weixin', 'statistics'])
            ->where($cond)
            ->find();
    }

    public function getUserAuthView($userId)
    {
        $user = UserModel::get($userId);
        $auth = $user->auth()->with(['view'])->where('type', 1)->find();
        if (empty($auth)) {
            return [];
        }
        return array_map(function ($i) {
            return $i['path'];
        }, $auth->view->toArray());
    }

    public function getUserAuthApi($userId, $controller)
    {
        $user = UserModel::get($userId);
        $auth = $user->auth()->with(['api'])->where('type', 1)->find();
        if (empty($auth)) {
            return [];
        }
        return explode('|', join('', array_map(function ($i) {
            return $i['actions'];
        }, array_filter($auth->api->toArray(), function ($j) use ($controller) {
            return $j['controller'] == $controller;
        }))));
    }
}
